import React, { useState } from 'react'
import './index.scss'
import logo from '../../../public/19.png'
import bottomImg from '../../../public/容器底部.png'
import encryptWithRSA from '../../utils/encryptWithRSA'
import { sendEmailCode } from '../../api/index.ts'
import { register } from '../../api/index.ts'
import { useCountdown } from '../../hooks/useCountdown'
// import { sendEmailCode } from '../../api/index'
import { useNavigate } from 'react-router-dom'

const Zc: React.FC = () => {
  const [formData, setFormData] = useState({
    email: '',
    verificationCode: '',
    password: '',
    confirmPassword: '',
    invitationCode: ''
  })
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const PUBLIC_KEY = `MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCuQd3gESx7VdIyRYUWjmjg61VIgUK6F45hClmqUMZ7xNiT5rlLM6e78osMvBF/yP7cVm7pK+NMCDWoVS1/AETpxJYqUlIC77ZAU8/MnP96IupnJL87vqhPcpdv7+VqLM38ls++yuD/F/HSoOQTv/leJh+dgE/4EYAJjOWFAbYfXwIDAQAB`
  const payload = {
    email: formData.email.trim(),
    code: formData.verificationCode.trim(),
    pwd1: encryptWithRSA(formData.password, PUBLIC_KEY),
    pwd2: encryptWithRSA(formData.confirmPassword, PUBLIC_KEY),
    invitationCode: formData.invitationCode?.trim() || undefined
  }
  const navigate = useNavigate()
  const { isCounting, startCountdown, getButtonText } = useCountdown()
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: value
    }))
  }

  const handleGetVerificationCode = async () => {
    if (!formData.email) {
      alert('请先输入邮箱')
      return
    }
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      alert('请输入有效的邮箱地址')
      return
    }
    // 这里添加获取验证码的逻辑
    startCountdown()
    const params = { email: formData.email }
    console.log('获取验证码', formData.email)
    const res = await sendEmailCode(params)
    if (res.status === 200) {
      alert('验证码已发送')
    }
  }

  const handleRegister = async () => {
    if (!formData.email || !formData.verificationCode || !formData.password || !formData.confirmPassword) {
      alert('输入内容')
      return
    }

    if (formData.password !== formData.confirmPassword) {
      alert('两次输入的密码不一致')
      return
    }

    setIsLoading(true)
    try {
      // 这里添加注册逻辑
      console.log('注册数据:', formData)
      // 模拟API调用
      const res = await register(payload)
      if (res.status === 200) {
        alert('注册成功')
        navigate('/login')
      }
    } catch {
      alert('注册失败，请重试')
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className='registerContainer'>
      {/* 背景装饰 */}

      {/* Logo */}
      <div className='logoContainer'>
        <img src={logo} alt="logo" />
      </div>

      {/* 注册表单 */}
      <div className='formContainer'>
        <div className='formCard'>
          {/* 邮箱输入 */}
          <div className='inputGroup'>
            <div className='inputIcon'>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" />
                <polyline points="22,6 12,13 2,6" />
              </svg>
            </div>
            <input
              type="email"
              name="email"
              placeholder="请输入邮箱"
              value={formData.email}
              onChange={handleInputChange}
              className='input'
            // rules={{ required: true ,message: '请输入邮箱' }}
            />
            <button
              type="button"
              className='verificationBtn'
              onClick={handleGetVerificationCode}
              disabled={isCounting}
            >
              {getButtonText()}
            </button>
          </div>

          {/* 验证码输入 */}
          <div className='inputGroup'>
            <div className='inputIcon'>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
                <path d="M9 12l2 2 4-4" />
              </svg>
            </div>
            <input
              type="text"
              name="verificationCode"
              placeholder="请输入验证码"
              value={formData.verificationCode}
              onChange={handleInputChange}
              className='input'
            />
          </div>

          {/* 密码输入 */}
          <div className='inputGroup'>
            <div className='inputIcon'>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
                <circle cx="12" cy="16" r="1" />
                <path d="M7 11V7a5 5 0 0 1 10 0v4" />
              </svg>
            </div>
            <input
              type={showPassword ? "text" : "password"}
              name="password"
              placeholder="请输入密码"
              value={formData.password}
              onChange={handleInputChange}
              className='input'
            />
            <button
              type="button"
              className='eyeBtn'
              onClick={() => setShowPassword(!showPassword)}
            >
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                {showPassword ? (
                  <>
                    <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24" />
                    <line x1="1" y1="1" x2="23" y2="23" />
                  </>
                ) : (
                  <>
                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
                    <circle cx="12" cy="12" r="3" />
                  </>
                )}
              </svg>
            </button>
          </div>

          {/* 确认密码输入 */}
          <div className='inputGroup'>
            <div className='inputIcon'>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
                <circle cx="12" cy="16" r="1" />
                <path d="M7 11V7a5 5 0 0 1 10 0v4" />
              </svg>
            </div>
            <input
              type={showConfirmPassword ? "text" : "password"}
              name="confirmPassword"
              placeholder="请再次输入密码"
              value={formData.confirmPassword}
              onChange={handleInputChange}
              className='input'
            />
            <button
              type="button"
              className='eyeBtn'
              onClick={() => setShowConfirmPassword(!showConfirmPassword)}
            >
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                {showConfirmPassword ? (
                  <>
                    <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24" />
                    <line x1="1" y1="1" x2="23" y2="23" />
                  </>
                ) : (
                  <>
                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
                    <circle cx="12" cy="12" r="3" />
                  </>
                )}
              </svg>
            </button>
          </div>

          {/* 邀请码输入 */}
          <div className='inputGroup'>
            <div className='inputIcon'>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
                <circle cx="12" cy="7" r="4" />
              </svg>
            </div>
            <input
              type="text"
              name="invitationCode"
              placeholder="请输入邀请码"
              value={formData.invitationCode}
              onChange={handleInputChange}
              className='input'
            />
            <span className='optionalText'>选填</span>
          </div>

          {/* 注册按钮 */}
          <button
            className='registerBtn'
            onClick={handleRegister}
            disabled={isLoading}
          >
            {isLoading ? '注册中...' : '注册'}
          </button>
        </div>
      </div>
      <div className='bottomContainer'>
        <img src={bottomImg} alt="" className='bottomImg'/>
      </div>
      {/* <Button onClick={startCountdown} disabled={isCounting}>{getButtonText()}</Button> */}
    </div>
  )
}

export default Zc